In [6]:
def add_numbers(x,y):
    return x+y

a = add_numbers
a(1,2)


Out[6]:
3

In [15]:
x = [1, 2, 4]

In [16]:
x.insert(2, 3) # list.insert(position, item)

In [17]:
x


Out[17]:
[1, 2, 3, 4]

In [18]:
x = 'This is a string'
print(x[0]) #first character
print(x[0:1]) #first character, but we have explicitly set the end character
print(x[0:2]) #first two characters


T
T
Th

In [26]:
x = 'This is a string'

pos = 0

for i in range(len(x) + 1):
    print(x[0:pos])
    pos += 1

pos -= 2

for i in range(len(x) + 1):
    print(x[0:pos])
    pos -= 1


T
Th
Thi
This
This 
This i
This is
This is 
This is a
This is a 
This is a s
This is a st
This is a str
This is a stri
This is a strin
This is a string
This is a strin
This is a stri
This is a str
This is a st
This is a s
This is a 
This is a
This is 
This is
This i
This 
This
Thi
Th
T

This is a strin

^ Looks like Augusto de Campos' poems ^.^


In [27]:
firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)


Christopher
Brooks

In [30]:
secondname = 'Christopher Arthur Hansen Brooks'.split(' ')[1]
secondname


Out[30]:
'Arthur'

In [31]:
thirdname = 'Christopher Arthur Hansen Brooks'.split(' ')[2]
thirdname


Out[31]:
'Hansen'

In [32]:
dict = {'Manuel' : 'manuel@company.com', 'Bill' : 'bill@ig.com'}
dict['Manuel']


Out[32]:
'manuel@company.com'

In [34]:
for email in dict:
    print(dict[email])


manuel@company.com
bill@ig.com

In [35]:
for email in dict.values():
    print(email)


manuel@company.com
bill@ig.com

In [36]:
for name in dict.keys():
    print(name)


Manuel
Bill

In [53]:
for name, email in dict.items():
    print(name)
    print(email)


Manuel
manuel@company.com
Bill
bill@ig.com

In [54]:
sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'}

sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'

print(sales_statement.format(sales_record['person'],
                             sales_record['num_items'],
                             sales_record['price'],
                             sales_record['num_items']*sales_record['price']))


Chris bought 4 item(s) at a price of 3.24 each for a total of 12.96

In [60]:
import csv

%precision 2 # float point precision for printing to 2

with open('mpg.csv') as csvfile: #read the csv file
    mpg = list(csv.DictReader(csvfile)) # https://docs.python.org/2/library/csv.html
    # csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
    
mpg[:3] # The first three dictionaries in our list.


Out[60]:
[{'': '1',
  'class': 'compact',
  'cty': '18',
  'cyl': '4',
  'displ': '1.8',
  'drv': 'f',
  'fl': 'p',
  'hwy': '29',
  'manufacturer': 'audi',
  'model': 'a4',
  'trans': 'auto(l5)',
  'year': '1999'},
 {'': '2',
  'class': 'compact',
  'cty': '21',
  'cyl': '4',
  'displ': '1.8',
  'drv': 'f',
  'fl': 'p',
  'hwy': '29',
  'manufacturer': 'audi',
  'model': 'a4',
  'trans': 'manual(m5)',
  'year': '1999'},
 {'': '3',
  'class': 'compact',
  'cty': '20',
  'cyl': '4',
  'displ': '2',
  'drv': 'f',
  'fl': 'p',
  'hwy': '31',
  'manufacturer': 'audi',
  'model': 'a4',
  'trans': 'manual(m6)',
  'year': '2008'}]

In [62]:
len(mpg) # list of 234 dictionaries


Out[62]:
234

In [64]:
mpg[0].keys() # the names of the colums


Out[64]:
dict_keys(['', 'manufacturer', 'model', 'fl', 'cyl', 'cty', 'trans', 'displ', 'class', 'drv', 'year', 'hwy'])

In [69]:
# How to find the average cty fuel economy across all cars. 
# All values in the dictionaries are strings, so we need to 
# convert to float.
sum(float(d['cty']) for d in mpg) / len(mpg)


Out[69]:
16.86

In [70]:
# Similarly this is how to find the average hwy fuel economy across
# all cars.
sum(float(d['hwy']) for d in mpg) / len(mpg)


Out[70]:
23.44

In [73]:
# Use set to return the unique values for the number of cylinders 
# the cars in our dataset have.

cylinders = set(d['cyl'] for d in mpg)
cylinders

# A set is an unordered collection of items. Every element is unique 
# (no duplicates) and must be immutable (which cannot be changed).

# >>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
# >>> set(x)
# set([1, 2, 3])


Out[73]:
{'4', '5', '6', '8'}

In [75]:
CtyMpgByCyl = [] # empty list to start the calculations

for c in cylinders: # iterate over all the cylinder levels
    summpg = 0
    cyltypecount = 0
    for d in mpg: # iterate over all dictionaries
        if d['cyl'] == c: # if the cylinder level type matches,
            summpg += float(d['cty']) # add the cty mpg
            cyltypecount += 1 # increment the count
    CtyMpgByCyl.append((c, summpg / cyltypecount)) # append the tuple ('cylinder', 'avg mpg')

CtyMpgByCyl.sort(key=lambda x: x[0])
CtyMpgByCyl

# the city fuel economy appears to be decreasing as the number of cylinders increases


Out[75]:
[('4', 21.01), ('5', 20.50), ('6', 16.22), ('8', 12.57)]

In [77]:
# Use set to return the unique values for the class types in our dataset.

vehicleclass = set(d['class'] for d in mpg) # what are the class types
vehicleclass


Out[77]:
{'2seater', 'compact', 'midsize', 'minivan', 'pickup', 'subcompact', 'suv'}

In [79]:
# how to find the average hwy mpg for each class of vehicle in our dataset.

HwyMpgByClass = []

for t in vehicleclass: # iterate over all the vehicle classes
    summpg = 0
    vclasscount = 0
    for d in mpg: # iterate over all dictionaries
        if d['class'] == t: # if the cylinder amount type matches,
            summpg += float(d['hwy']) # add the hwy mpg
            vclasscount += 1 # increment the count
    HwyMpgByClass.append((t, summpg / vclasscount)) # append the tuple ('class', 'avg mpg')

HwyMpgByClass.sort(key=lambda x: x[1])
HwyMpgByClass


Out[79]:
[('pickup', 16.88),
 ('suv', 18.13),
 ('minivan', 22.36),
 ('2seater', 24.80),
 ('midsize', 27.29),
 ('subcompact', 28.14),
 ('compact', 28.30)]

The Python Programming Language: Dates and Times


In [81]:
import datetime as dt
import time as tm

In [82]:
# time returns the current time in seconds since the Epoch. (January 1st, 1970)
tm.time()


Out[82]:
1497033576.15

In [83]:
# Convert the timestamp to datetime.

dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow


Out[83]:
datetime.datetime(2017, 6, 9, 15, 40, 16, 639355)

In [84]:
dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime


Out[84]:
(2017, 6, 9, 15, 40, 16)

In [85]:
# timedelta is a duration expressing the difference between two dates.

delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta


Out[85]:
datetime.timedelta(100)

In [3]:
a = (1, 2)

In [4]:
type(a)


Out[4]:
tuple

In [5]:
['a', 'b', 'c'] + [1, 2, 3]


Out[5]:
['a', 'b', 'c', 1, 2, 3]

In [6]:
type(lambda x: x+1)


Out[6]:
function

In [7]:
[x**2 for x in range(10)]


Out[7]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [19]:
str = "Python é muito legal"
lista = []
soma = 0

lista = str.split()
lista


Out[19]:
6

In [20]:
len(lista[0])


Out[20]:
6

In [21]:
for i in lista:
    soma += len(i)

In [22]:
soma


Out[22]:
17

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: